<!-- 正文开始 -->
<div class="layui-fluid" id="mainRole">
    <div class="layui-card">
        <div class="layui-card-header">筛选条件</div>
        <div class="layui-card-body">
            <form class="layui-form layui-form-pane">
                <div class="layui-row layui-col-space10">
                    <div class="layui-col-md3 layui-col-sm12 layui-col-xs12">
                        <label class="layui-form-label">角色名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="roleName" autocomplete="off" placeholder="请输入角色名称"
                                   class="layui-input">
                        </div>
                    </div>
                    <div class="layui-col-md3 layui-col-sm12 layui-col-xs12">
                        <label class="layui-form-label">状态</label>
                        <div class="layui-input-block">
                            <select id="queryStateRole" name="state"></select>
                        </div>
                    </div>
                    <div class="layui-col-md2 layui-col-sm12 layui-col-xs12">
                        <button class="layui-btn layui-btn-fluid" lay-submit
                                id="querySubmitRole" lay-filter="querySubmitRole">筛选
                        </button>
                    </div>
                    <div class="layui-col-md1 layui-col-sm12 layui-col-xs12">
                        <button type="reset" class="layui-btn layui-btn-primary layui-btn-fluid">重置</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div class="layui-card">
        <table id="listRole" lay-filter="listRole"></table>
    </div>
</div>

<!-- 表格批量工具栏 -->
<script type="text/html" id="listToolbarRole">
    <div class="layui-btn-container">
        {{# if(layui.admin.hasPerm(layui.reqApi.admin.role.createOrUpdate.getPermissionUrl("POST"))){ }}
        <a class="layui-btn layui-btn-sm" lay-event="listToolbarSaveRole">
            <i class="layui-icon">&#xe61f;</i>添加角色</a>
        {{# } if(layui.admin.hasPerm(layui.reqApi.admin.role.setRoleResource.getPermissionUrl("PUT"))){ }}
        <a class="layui-btn layui-btn-sm layui-btn-normal" lay-event="listToolbarSetRoleResource">
            <i class="layui-icon">&#xe66e;</i>角色菜单</a>
        {{# } if(layui.admin.hasPerm(layui.reqApi.admin.role.batchUpdateState.getPermissionUrl("PUT"))){ }}
        <a class="layui-btn layui-btn-sm layui-btn-primary" lay-event="listToolbarEnableRole">
            <i class="layui-icon">&#x1005;</i>批量启用</a>
        <a class="layui-btn layui-btn-sm layui-btn-primary" lay-event="listToolbarDisableRole">
            <i class="layui-icon">&#x1007;</i>批量禁用</a>
        {{# } if(layui.admin.hasPerm(layui.reqApi.admin.role.batchDelete.getPermissionUrl("POST"))){ }}
        <a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="listToolbarDelRole">
            <i class="layui-icon">&#xe640;</i>批量删除</a>
        {{# } }}
    </div>
</script>

<!-- 表格状态模板 -->
<script type="text/html" id="listStateTplRole">
    {{#  if(layui.reqEnum.state.normal === d.state){ }}
    <span style="color: #009688;">{{ d.stateStr }}</span>
    {{#  } else if(layui.reqEnum.state.disable === d.state) { }}
    <span style="color: #d2d2d2;">{{ d.stateStr }}</span>
    {{#  } else { }}
    <span>{{ d.state_str }}</span>
    {{#  } }}
</script>

<!-- 表格操作模板 -->
<script type="text/html" id="listToolRole">
    {{# if(layui.admin.hasPerm(layui.reqApi.admin.role.setRoleResource.getPermissionUrl("PUT"))){ }}
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="listToolSetRoleResource"> 角色菜单 </a>
    {{# } if(layui.admin.hasPerm(layui.reqApi.admin.role.createOrUpdate.getPermissionUrl("POST"))){ }}
    <a class="layui-btn layui-btn-xs" lay-event="listToolUpdateRole"> 编辑 </a>
    {{# } if(layui.admin.hasPerm(layui.reqApi.admin.role.batchDelete.getPermissionUrl("POST"))){ }}
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="listToolDelRole"> 删除 </a>
    {{# } }}
</script>

<!-- 新增或者修改 -->
<script type="text/html" id="suContainerRole">
    <form lay-filter="suFormRole" class="layui-form layui-form-pane">
        <input name="id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label red-star-label">角色名称</label>
            <div class="layui-input-block">
                <input name="roleName" placeholder="请输入角色名称" type="text" class="layui-input" maxlength="64"
                       lay-verType="tips" lay-verify="required"/>
            </div>
        </div>
        <div class="layui-form-item  layui-form-text">
            <label class="layui-form-label layui-btn-fluid">备注</label>
            <div class="layui-input-block">
                <textarea name="remark" placeholder="请输入备注" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="suSubmitRole" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'table', 'admin', 'setter', 'form', 'reqApi', 'reqEnum', 'promiseReq', 'dtree'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var table = layui.table;
        var admin = layui.admin;
        var setter = layui.setter;
        var form = layui.form;
        var reqApi = layui.reqApi;
        var reqEnum = layui.reqEnum;
        var promiseReq = layui.promiseReq;
        var dtree = layui.dtree;

        // 引用对象
        var main = 'mainRole'
            , queryState = 'queryStateRole'
            , querySubmit = 'querySubmitRole'
            , list = 'listRole'
            , listToolbar = 'listToolbarRole'
            , listToolbarSave = 'listToolbarSaveRole'
            , listToolbarSetRoleResource = 'listToolbarSetRoleResource'
            , listToolbarEnable = 'listToolbarEnableRole'
            , listToolbarDisable = 'listToolbarDisableRole'
            , listToolbarDel = 'listToolbarDelRole'
            , listStateTpl = 'listStateTplRole'
            , listTool = 'listToolRole'
            , listToolSetRoleResource = 'listToolSetRoleResource'
            , listToolUpdate = 'listToolUpdateRole'
            , listToolDel = 'listToolDelRole'
            , suContainer = 'suContainerRole'
            , suForm = 'suFormRole'
            , suSubmit = 'suSubmitRole'

        var setRoleResourceOpen = 'setRoleResourceOpenRole'
            , setRoleResourceTree = 'setRoleResourceTreeRole'
            , menuTree = 'menuTreeRole'
            , suOpen = 'suOpenRole'

        // 等待框
        admin.showLoading('#' + main, 1, '.5');

        // 字典
        var listStateReq = promiseReq.req({
            url: reqApi.admin.home.enum.restfulFormat({enumName: 'StateEnum'})
            , success: function (rs) {
                var dataList = rs.data;
                var str = '<option value="">请选择</option>';
                for (var i = 0; i < dataList.length; i++) {
                    var data = dataList[i];
                    str += '<option value="' + data.value + '">' + data.msg + '</option>'
                }
                $('#' + queryState).empty();
                $('#' + queryState).append(str);
            }
        });

        // 筛选
        form.on('submit(' + querySubmit + ')', function (obj) {
            admin.showLoading('#' + main, 1, '.5');
            listRender(obj.field);
            return false;
        });

        // 表格筛选触发
        function listQuery() {
            $('#' + querySubmit).click();
        }

        // 执行
        listRender();

        // 表格渲染
        function listRender(param) {
            // 权限设置
            var toolbar = '#' + listToolbar;
            var handle = [{title: '操作', align: "center", templet: '#' + listTool, width: 200, fixed: 'left',}];
            if (!admin.hasPerm(layui.reqApi.admin.role.createOrUpdate.getPermissionUrl("POST"))
                && !admin.hasPerm(layui.reqApi.admin.role.setRoleResource.getPermissionUrl("PUT"))
                && !admin.hasPerm(layui.reqApi.admin.role.batchUpdateState.getPermissionUrl("PUT"))
                && !admin.hasPerm(layui.reqApi.admin.role.batchDelete.getPermissionUrl("POST"))) {
                toolbar = false;
            }
            if (!admin.hasPerm(layui.reqApi.admin.role.createOrUpdate.getPermissionUrl("POST"))
                && !admin.hasPerm(layui.reqApi.admin.role.setRoleResource.getPermissionUrl("PUT"))
                && !admin.hasPerm(layui.reqApi.admin.role.batchDelete.getPermissionUrl("POST"))) {
                handle = []
            }

            // 初始化
            table.render({
                elem: '#' + list
                , toolbar: toolbar
                , height: 'full-300'
                , headers: {Authorization: setter.getBearerToken()}
                , url: reqApi.admin.role.list
                , cellMinWidth: 150
                , cols: [[].concat(handle).concat([
                    {title: '序号', type: 'numbers', width: 100},
                    {type: 'checkbox', width: 60},
                    {title: '角色名称', field: 'roleName', align: 'left'},
                    {title: '备注', field: 'remark', align: 'left', minWidth: 250},
                    {title: '状态', field: 'state', align: 'center', templet: '#' + listStateTpl, width: 60},
                    {title: '修改时间', field: 'gmtModified', align: 'center'},
                    {title: '创建时间', field: 'gmtCreate', align: 'center'}
                ])]
                , where: param
                , done: function () {
                    Promise.all([listStateReq]).finally(function () {
                        form.render();
                        admin.removeLoading('#' + main);
                    });
                }
                , request: {pageName: 'cursor', limitName: 'limit'}
                , parseData: function (rs) {
                    return {"code": rs.code, "msg": rs.msg, "count": rs.data.total, "data": rs.data.records};
                }
                , response: {statusCode: 200}
                , defaultToolbar: []
                , page: true
                , limit: 50
                , loading: true
                , text: {none: '暂无相关数据'}
            });
        }

        // 监听表格批量工具栏
        table.on('toolbar(' + list + ')', function (obj) {
            switch (obj.event) {
                case listToolbarSave:
                    suRender();
                    break;
                case listToolbarSetRoleResource:
                    var data = table.checkStatus(list).data;
                    if (0 === data.length) {
                        layer.msg('请勾选要操作的数据', {time: 1000});
                        break;
                    }
                    var idList = [];
                    for (var i in data) {
                        idList[i] = data[i].id;
                    }
                    setRoleResourceRender(idList);
                    break;
                case listToolbarEnable:
                    updateStateRender(reqEnum.state.normal);
                    break;
                case listToolbarDisable:
                    updateStateRender(reqEnum.state.disable);
                    break;
                case listToolbarDel:
                    var data = table.checkStatus(list).data;
                    if (0 === data.length) {
                        layer.msg('请勾选要删除的数据', {time: 1000});
                        break;
                    }
                    var idList = [];
                    for (var i in data) {
                        idList[i] = data[i].id;
                    }
                    delRender(idList);
                    break;
            }
        });

        // 监听表格操作行
        table.on('tool(' + list + ')', function (obj) {
            var id = obj.data.id;
            switch (obj.event) {
                case listToolSetRoleResource:
                    setRoleResourceRender([id]);
                    break;
                case listToolUpdate:
                    suRender(id);
                    break;
                case listToolDel:
                    delRender([id]);
                    break;
            }
        });

        // 角色菜单
        function setRoleResourceRender(roleIdList) {
            admin.open({
                id: setRoleResourceOpen
                , title: '角色菜单'
                , type: 1
                , shadeClose: true
                , area: ['auto', '80%']
                , content:
                    '<div style="padding-bottom:15px;">' +
                    '<span>操作：</span>' +
                    '<button class="layui-btn layui-btn-xs layui-btn-normal" dtree-id="' + setRoleResourceTree + '" ' +
                    'dtree-menu="chooseAll">全选</button>' +
                    '<button class="layui-btn layui-btn-xs layui-btn-primary" dtree-id="' + setRoleResourceTree + '" ' +
                    'dtree-menu="cancelAll">全不选</button>' +
                    '<button class="layui-btn layui-btn-xs" dtree-id="' + setRoleResourceTree + '" ' +
                    'dtree-menu="moveDown">展开</button>' +
                    '<button class="layui-btn layui-btn-xs layui-btn-primary" dtree-id="' + setRoleResourceTree + '" ' +
                    'dtree-menu="moveUp">折叠</button>' +
                    '<button class="layui-btn layui-btn-xs layui-btn-danger" dtree-id="' + setRoleResourceTree + '" ' +
                    'dtree-menu="refresh">重置</button>' +
                    '</div>' +
                    '<ul id=' + setRoleResourceTree + ' class="dtree" data-id="0"></ul>'
                , btn: ['确认选择']
                , success: function (layero, index) {
                    admin.showLoading('#' + setRoleResourceOpen, 1, '.5');
                    var roleId = '';
                    if (1 == roleIdList.length) {
                        roleId = '?roleId=' + roleIdList[0];
                    }
                    admin.req({
                        url: reqApi.admin.resource.all + roleId
                        , type: 'get'
                        , complete: function () {
                            admin.removeLoading('#' + setRoleResourceOpen);
                        }
                        , success: function (rs) {
                            if (!rs || !rs.data || 0 === rs.data.length) {
                                layer.msg('暂无资源', {time: 1000});
                                return;
                            }
                            menuTree = dtree.render({
                                elem: '#' + setRoleResourceTree
                                , data: rs.data
                                , response: {rootName: "result", treeId: "id", parentId: "parentId", title: "name"}
                                , skin: "resource"
                                , dot: false
                                , initLevel: 7
                                , nodeIconArray: {'1': {'open': 'dtree-icon-move-down', 'close': 'dtree-icon-move-up'}}
                                , leafIconArray: {'2': 'dtree-icon-home1'}
                                , icon: ['1', '2']
                                , dataFormat: 'list'
                                , dataStyle: 'layuiStyle'
                                , checkbar: true
                                , menubar: true
                                , menubarTips: {
                                    freedom: [
                                        {
                                            menubarId: "chooseAll", handler: function () {
                                                menuTree.initAllChoose();
                                            }
                                        }
                                        , {
                                            menubarId: "cancelAll", handler: function () {
                                                menuTree.initAllCancel();
                                            }
                                        }
                                    ]
                                    , group: [] // 按钮组制空
                                }
                            });
                        }
                    });
                }
                , yes: function (index) {
                    var resourceIdList = [];
                    var param = menuTree.getCheckbarNodesParam();
                    for (var i in param) {
                        if (!param[i].nodeId) {
                            return;
                        }
                        resourceIdList.push(param[i].nodeId);
                    }
                    new Promise(function (resolve, reject) {
                        if (0 === resourceIdList.length) {
                            layer.confirm('由于没有选择菜单，所操作的角色菜单将会被清空，请确认？', {
                                skin: 'layui-layer-admin'
                                , btn: ['确定', '取消']
                            }, function (confirmIndex) {
                                resolve();
                                layer.close(confirmIndex);
                            }, function (confirmIndex) {
                                reject();
                                layer.close(confirmIndex);
                            });
                        } else {
                            resolve();
                        }
                    }).then(function () {
                        var reqEL = layer.msg('操作执行中', {icon: 16, shade: 0.01, time: 6000});
                        admin.req({
                            url: reqApi.admin.role.setRoleResource
                            , type: 'put'
                            , data: {roleIdList: roleIdList, resourceIdList: resourceIdList}
                            , complete: function () {
                                layer.close(reqEL);
                            }
                            , success: function () {
                                listQuery();
                                layer.close(index);
                                layer.msg('操作成功', {offset: '15px', icon: 1, time: 1000});
                            }
                        });
                    }).catch(function () {
                    })
                }
            });
        }

        // 启用或者禁用操作
        function updateStateRender(state) {
            var data = table.checkStatus(list).data;
            if (0 === data.length) {
                layer.msg('请勾选要操作的数据', {time: 1000});
                return;
            }
            var idList = [];
            for (var i in data) {
                idList[i] = data[i].id;
            }
            layer.confirm('确定操作所选信息？', {
                skin: 'layui-layer-admin'
                , btn: ['确定', '取消'] //按钮
            }, function () {
                var reqEL = layer.msg('操作执行中', {icon: 16, shade: 0.01, time: 6000});
                admin.req({
                    url: reqApi.admin.role.batchUpdateState
                    , type: 'put'
                    , data: {'idList': idList, 'state': state}
                    , complete: function () {
                        layer.close(reqEL);
                    }
                    , success: function () {
                        listQuery();
                        layer.msg('操作成功', {offset: '15px', icon: 1, time: 1000});
                    }
                });
            }, function () {
            });
        }

        // 删除操作
        function delRender(idList) {
            layer.confirm('确定删除所选信息？', {
                skin: 'layui-layer-admin'
                , btn: ['确定', '取消']
            }, function () {
                var reqEL = layer.msg('操作执行中', {icon: 16, shade: 0.01, time: 6000});
                admin.req({
                    url: reqApi.admin.role.batchDelete
                    , type: 'post'
                    , data: idList
                    , complete: function () {
                        layer.close(reqEL);
                    }
                    , success: function () {
                        layer.msg('操作成功', {offset: '15px', icon: 1, time: 500});
                        listQuery();
                    }
                });
            }, function () {
            });
        }

        // 新增或者修改
        function suRender(id) {
            admin.open({
                id: suOpen
                , type: 1
                , title: '新增 or 修改'
                , shadeClose: true
                , content: $('#' + suContainer).html()
                , success: function (layero, index) {
                    admin.showLoading('#' + suOpen, 1, '.5');
                    suSubmitRender(index);
                    if (id) {
                        var infoReq = promiseReq.req({
                            url: reqApi.admin.role.get.restfulFormat({id: id})
                            , success: function (rs) {
                                var data = rs.data;
                                form.val(suForm, {
                                    "id": id
                                    , "roleName": data.roleName
                                    , "remark": data.remark
                                });
                            }
                        });
                        Promise.all([infoReq]).finally(function () {
                            admin.removeLoading('#' + suOpen);
                            form.render();
                        });
                    } else {
                        admin.removeLoading('#' + suOpen);
                        form.render();
                    }
                }
            });
        }

        // 初始化新增或者修改提交
        function suSubmitRender(index) {
            form.on('submit(' + suSubmit + ')', function (obj) {
                var reqEL = layer.msg('操作执行中', {icon: 16, shade: 0.01, time: 6000});
                admin.req({
                    url: reqApi.admin.role.createOrUpdate
                    , type: 'post'
                    , data: obj.field
                    , complete: function () {
                        layer.close(reqEL);
                    }
                    , success: function () {
                        layer.msg('操作成功', {offset: '15px', icon: 1, time: 500});
                        layer.close(index);
                        listQuery();
                    }
                });
                return false;
            });
        }
    });
</script>